package ynu.edu.achitecturework.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class FboxService {

    @Value("${fbox.client-id}")
    private String clientId;

    @Value("${fbox.client-secret}")
    private String clientSecret;

    private final RestTemplate restTemplate;
    private String accessToken;

    public FboxService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void login() {
        String url = "https://fbox360.com/idserver/core/connect/token";

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("scope", "fbox");
        params.add("client_id", clientId);
        params.add("client_secret", clientSecret);
        params.add("grant_type", "client_credentials");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                this.accessToken = (String) response.getBody().get("access_token");
                log.info("Successfully obtained access token");
            }
        } catch (Exception e) {
            log.error("Failed to login to Fbox: {}", e.getMessage());
            throw e;
        }
    }

    public List<Map<String, Object>> getSensorData(String boxNo, List<String> deviceIds) {
        if (accessToken == null) {
            login();
        }

        String url = "https://fbox360.com/api/v2/dmon/value/get?boxNo=" + boxNo;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(accessToken);

        Map<String, List<String>> requestBody = Map.of("ids", deviceIds);

        HttpEntity<Map<String, List<String>>> request = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<List> response = restTemplate.postForEntity(url, request, List.class);
            List<Map<String, Object>> data = response.getBody();

            // 打印接收到的数据
            if (data != null) {
                data.forEach(item -> log.info("Received sensor data: {}", item));
            }

            return data;
        } catch (Exception e) {
            log.error("Failed to get sensor data: {}", e.getMessage());
            throw e;
        }
    }
}